#!/bin/sh
# 监控服务一键部署脚本 - 确保使用Unix换行符(LF)

# 配置变量
RELEASE_URL="http://gitee.com/t88t/omr-screen_-web-serial/releases/download/v0.1.1/monitor_package.rar"
WORK_DIR="/tmp"
EXTRACT_DIR="$WORK_DIR/extract_temp"
SERVICE_NAME="monitor_services"
INSTALL_DIR="/root/monitor"

echo "=== 开始部署流程 ==="
echo "1. 检查服务状态..."

# 检查进程是否运行
if pgrep -f "screen|bps|power" > /dev/null || [ -f "/etc/init.d/$SERVICE_NAME" ]; then
  echo "检测到服务正在运行或服务文件存在，执行清理..."
  # 停止服务
  if [ -f "/etc/init.d/$SERVICE_NAME" ]; then
    echo "停止服务..."
    /etc/init.d/$SERVICE_NAME stop
    echo "禁用服务自启动..."
    /etc/init.d/$SERVICE_NAME disable
    sleep 2
  else
    # 如果没有服务脚本但进程在运行，手动终止
    echo "手动终止相关进程..."
    killall screen 2>/dev/null
    killall bps 2>/dev/null
    killall power 2>/dev/null
    sleep 2
  fi
  
  # 删除旧的安装目录
  if [ -d "$INSTALL_DIR" ]; then
    echo "删除旧的安装目录..."
    rm -rf "$INSTALL_DIR"
  fi
fi

echo "2. 准备工作目录..."
cd "$WORK_DIR"
rm -f package.rar
rm -rf "$EXTRACT_DIR"
mkdir -p "$EXTRACT_DIR"

echo "3. 检查并安装必要工具..."
# 只有在需要时才更新包列表
NEED_UPDATE=0

# 检查wget是否安装
if ! command -v wget &> /dev/null; then
  echo "wget未安装，将安装wget..."
  NEED_UPDATE=1
fi

# 检查解压工具是否安装
if ! command -v unrar &> /dev/null && ! command -v unzip &> /dev/null; then
  echo "未安装解压工具，将安装unrar或unzip..."
  NEED_UPDATE=1
fi

# 只有在需要安装新工具时才更新软件源
if [ $NEED_UPDATE -eq 1 ]; then
  echo "更新软件源..."
  opkg update
fi

# 安装wget（如果未安装）
if ! command -v wget &> /dev/null; then
  echo "安装wget..."
  opkg install wget
  
  # 检查安装结果
  if ! command -v wget &> /dev/null; then
    echo "错误: 无法安装wget"
    exit 1
  fi
else
  echo "wget已安装，跳过安装"
fi

# 检查并安装解压工具
if ! command -v unrar &> /dev/null; then
  echo "安装unrar..."
  opkg install unrar
  
  # 如果unrar安装失败，尝试安装unzip
  if ! command -v unrar &> /dev/null; then
    echo "unrar安装失败，尝试安装unzip..."
    if ! command -v unzip &> /dev/null; then
      opkg install unzip
    fi
    
    # 检查unzip是否成功安装
    if ! command -v unzip &> /dev/null; then
      echo "错误: 无法安装解压工具 (unrar或unzip)"
      echo "请手动安装解压工具后再运行此脚本"
      exit 1
    fi
  fi
else
  echo "unrar已安装，跳过安装"
fi

echo "4. 下载文件..."
wget "$RELEASE_URL" -O package.rar
if [ $? -ne 0 ]
then
  echo "下载失败"
  rm -rf "$EXTRACT_DIR"
  exit 1
fi

echo "5. 解压文件..."
cd "$EXTRACT_DIR"
# 优先使用unrar
if command -v unrar &> /dev/null; then
  echo "使用unrar解压..."
  unrar x "$WORK_DIR/package.rar"
  if [ $? -ne 0 ]; then
    echo "unrar解压失败，尝试使用unzip..."
    if command -v unzip &> /dev/null; then
      unzip "$WORK_DIR/package.rar"
      if [ $? -ne 0 ]; then
        echo "解压失败，文件可能已损坏"
        cd "$WORK_DIR" 
        rm -rf "$EXTRACT_DIR" package.rar
        exit 1
      fi
    else
      echo "错误: 无法解压文件，unrar失败且unzip不可用"
      cd "$WORK_DIR" 
      rm -rf "$EXTRACT_DIR" package.rar
      exit 1
    fi
  fi
else
  # 如果没有unrar，使用unzip
  if command -v unzip &> /dev/null; then
    echo "使用unzip解压..."
    unzip "$WORK_DIR/package.rar"
    if [ $? -ne 0 ]; then
      echo "解压失败，文件可能已损坏"
      cd "$WORK_DIR" 
      rm -rf "$EXTRACT_DIR" package.rar
      exit 1
    fi
  else
    echo "错误: 系统中没有可用的解压工具"
    cd "$WORK_DIR" 
    rm -rf "$EXTRACT_DIR" package.rar
    exit 1
  fi
fi

echo "6. 检查文件..."
if [ -d "monitor_package" ]
then
  cd monitor_package
else
  if [ -d "$EXTRACT_DIR/monitor_package" ]
  then
    cd "$EXTRACT_DIR/monitor_package"
  else
    echo "未找到monitor_package目录"
    cd "$WORK_DIR"
    rm -rf "$EXTRACT_DIR" package.rar
    exit 1
  fi
fi

echo "7. 授予权限..."
chmod +x *.sh 2>/dev/null
if [ -d "monitor" ]
then
  find "monitor" -name "*.sh" -exec chmod +x {} \; 2>/dev/null
fi

# 获取当前目录的绝对路径
PACKAGE_DIR=$(pwd)

echo "8. 安装监控服务..."
# 在路由器上创建目录
echo "8.1 创建目录..."
mkdir -p "$INSTALL_DIR"

# 复制程序文件到目标目录
echo "8.2 复制程序文件..."
cp -f "$PACKAGE_DIR"/monitor/* "$INSTALL_DIR"/

# 设置执行权限
echo "8.3 设置执行权限..."
chmod +x "$INSTALL_DIR"/screen
chmod +x "$INSTALL_DIR"/bps
chmod +x "$INSTALL_DIR"/power

# 创建启动脚本
echo "8.4 设置启动脚本..."
cat > /etc/init.d/$SERVICE_NAME << 'EOF'
#!/bin/sh
# OpenMPTCRouter启动脚本 - 用于启动监控服务

case "$1" in
  start)
    echo "Starting screen, bps and power services"
    # 创建日志目录
    mkdir -p /var/log/monitor
    cd /root/monitor
    /root/monitor/screen > /var/log/monitor/screen.log 2>&1 &
    /root/monitor/bps > /var/log/monitor/bps.log 2>&1 &
    /root/monitor/power > /var/log/monitor/power.log 2>&1 &
    ;;
  stop)
    echo "Stopping screen, bps and power services"
    killall screen
    killall bps
    killall power
    ;;
  restart)
    $0 stop
    sleep 1
    $0 start
    ;;
  status)
    echo "Services status:"
    ps | grep -E "screen|bps|power" | grep -v grep
    ;;
  enable)
    # 移除可能存在的旧链接
    [ -L /etc/rc.d/S99monitor_services ] && rm -f /etc/rc.d/S99monitor_services
    
    # 尝试不同的方法启用自启动
    # 方法1：标准rc.d目录
    if [ -d /etc/rc.d ]; then
      ln -sf /etc/init.d/monitor_services /etc/rc.d/S99monitor_services
      echo "Services enabled at startup via /etc/rc.d/"
    # 方法2：OpenWrt常见启动目录
    elif [ -d /etc/rc.boot ]; then
      ln -sf /etc/init.d/monitor_services /etc/rc.boot/S99monitor_services
      echo "Services enabled at startup via /etc/rc.boot/"
    # 方法3：添加到rc.local文件
    else
      # 确保rc.local存在
      [ ! -f /etc/rc.local ] && echo "#!/bin/sh" > /etc/rc.local
      
      # 移除旧的条目
      grep -v "monitor_services" /etc/rc.local > /etc/rc.local.tmp
      
      # 在exit 0前添加启动命令
      sed -i '/exit 0/i /etc/init.d/monitor_services start' /etc/rc.local.tmp
      
      # 确保文件以exit 0结尾
      echo "exit 0" >> /etc/rc.local.tmp
      
      # 替换原文件
      mv /etc/rc.local.tmp /etc/rc.local
      chmod +x /etc/rc.local
      
      echo "Services enabled at startup via /etc/rc.local"
    fi
    ;;
  disable)
    # 移除所有可能的启动链接
    [ -L /etc/rc.d/S99monitor_services ] && rm -f /etc/rc.d/S99monitor_services
    [ -L /etc/rc.boot/S99monitor_services ] && rm -f /etc/rc.boot/S99monitor_services
    
    # 从rc.local中移除
    if [ -f /etc/rc.local ]; then
      grep -v "monitor_services" /etc/rc.local > /etc/rc.local.tmp
      mv /etc/rc.local.tmp /etc/rc.local
      chmod +x /etc/rc.local
    fi
    
    echo "Services disabled at startup"
    ;;
  *)
    echo "Usage: monitor_services {start|stop|restart|status|enable|disable}"
    exit 1
    ;;
esac

exit 0
EOF

# 设置启动脚本权限
chmod +x /etc/init.d/$SERVICE_NAME

echo "8.5 配置服务自启动..."
# 启用服务
/etc/init.d/$SERVICE_NAME enable

# 尝试多种方式确保自启动
echo "尝试方法2: 添加到rc.local"
if [ -f /etc/rc.local ]; then
  # 如果已经存在启动命令则移除
  grep -v "monitor_services" /etc/rc.local > /tmp/rc.local.tmp
  # 在exit 0之前添加启动命令
  sed -i '/exit 0/i /etc/init.d/monitor_services start' /tmp/rc.local.tmp
  # 确保有exit 0
  echo "exit 0" >> /tmp/rc.local.tmp
  # 替换原文件
  mv /tmp/rc.local.tmp /etc/rc.local
  chmod +x /etc/rc.local
else
  # 创建rc.local
  echo "#!/bin/sh" > /etc/rc.local
  echo "/etc/init.d/monitor_services start" >> /etc/rc.local
  echo "exit 0" >> /etc/rc.local
  chmod +x /etc/rc.local
fi

echo "尝试方法3: 添加到crontab"
# 移除旧的crontab条目
(crontab -l 2>/dev/null | grep -v "monitor_services") | crontab -

# 添加新的启动条目
(crontab -l 2>/dev/null; echo "@reboot /etc/init.d/monitor_services start") | crontab -

echo "8.6 重启服务..."
# 重启服务
/etc/init.d/$SERVICE_NAME restart

echo "9. 清理文件..."
cd "$WORK_DIR"
rm -f package.rar
rm -rf "$EXTRACT_DIR"

echo ""
echo "=== 部署完成 ==="
echo "监控服务已成功安装并设置为开机自动启动"
echo ""
echo "服务控制命令："
echo "  启动：/etc/init.d/monitor_services start"
echo "  停止：/etc/init.d/monitor_services stop"
echo "  重启：/etc/init.d/monitor_services restart"
echo "  查看状态：/etc/init.d/monitor_services status"
echo "  开机启动：/etc/init.d/monitor_services enable"
echo "  停止开机启动：/etc/init.d/monitor_services disable"
echo ""
echo "Web界面访问: http://路由器IP:8080" 